package gac.helloworld;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class AlarmDbAdapter {

	public static final String KEY_WARNTIME = "warntime";
	public static final String KEY_MINUTE = "minute";
	public static final String KEY_HOUR = "hour";
	public static final String KEY_MONTH = "month";
	public static final String KEY_DAY = "day";
	public static final String KEY_YEAR = "year";
	public static final String KEY_DESTINATION = "destination";
	public static final String KEY_ISON = "isOn"; //value of 0 means off, value of 1 means on
	public static final String KEY_ROWID = "_id";

	private static final String TAG = "AlarmDbAdapter";
	private DatabaseHelper mDbHelper;
	private SQLiteDatabase mDb;

	/**
	 * Database creation sql statement
	 */
	private static final String DATABASE_CREATE = "create table alarms (_id integer primary key autoincrement, "
			+ "destination text not null, hour integer, minute integer, "
			+ "warntime integer, month integer, day integer, year integer, isOn integer);";

	private static final String DATABASE_NAME = "data";
	private static final String DATABASE_TABLE = "alarms";
	private static final int DATABASE_VERSION = 2;

	private final Context mCtx;

	private static class DatabaseHelper extends SQLiteOpenHelper {

		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(DATABASE_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
					+ newVersion + ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS alarms");
			onCreate(db);
		}
	}

	/**
	 * Constructor - takes the context to allow the database to be
	 * opened/created
	 * 
	 * @param ctx
	 *            the Context within which to work
	 */
	public AlarmDbAdapter(Context ctx) {
		this.mCtx = ctx;
	}

	/**
	 * Open the Alarms database. If it cannot be opened, try to create a new
	 * instance of the database. If it cannot be created, throw an exception to
	 * signal the failure
	 * 
	 * @return this (self reference, allowing this to be chained in an
	 *         initialization call)
	 * @throws SQLException
	 *             if the database could be neither opened or created
	 */
	public AlarmDbAdapter open() throws SQLException {

		mDbHelper = new DatabaseHelper(mCtx);
		mDb = mDbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		mDbHelper.close();
	}

	/**
	 * Create a new Alarm using the title and body provided. If the Alarm is
	 * successfully created return the new rowId for that Alarm, otherwise
	 * return a -1 to indicate failure.
	 * 
	 * @param title
	 *            the title of the Alarm
	 * @param body
	 *            the body of the Alarm
	 * @return rowId or -1 if failed
	 */
	public long createAlarm(String destination, int hour, int minute,
			int warntime, int month, int day, int year, int isOn) {
		ContentValues initialValues = new ContentValues();
		initialValues.put(KEY_DESTINATION, destination);
		initialValues.put(KEY_HOUR, hour);
		initialValues.put(KEY_MINUTE, minute);
		initialValues.put(KEY_WARNTIME, warntime);
		initialValues.put(KEY_MONTH, month);
		initialValues.put(KEY_DAY, day);
		initialValues.put(KEY_YEAR, year);
		initialValues.put(KEY_ISON, isOn);

		return mDb.insert(DATABASE_TABLE, null, initialValues);
	}

	/**
	 * Delete the Alarm with the given rowId
	 * 
	 * @param rowId
	 *            id of Alarm to delete
	 * @return true if deleted, false otherwise
	 */
	public boolean deleteAlarm(long rowId) {

		return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
	}

	/**
	 * Return a Cursor over the list of all Alarms in the database
	 * 
	 * @return Cursor over all Alarms
	 */
	public Cursor fetchAllAlarms() {

		return mDb.query(DATABASE_TABLE,
				new String[] { KEY_ROWID, KEY_DESTINATION, KEY_HOUR,
						KEY_MINUTE, KEY_WARNTIME, KEY_MONTH, KEY_DAY, KEY_YEAR, KEY_ISON}, null, null, null,
				null, null);
	}

	/**
	 * Return a Cursor positioned at the Alarm that matches the given rowId
	 * 
	 * @param rowId
	 *            id of Alarm to retrieve
	 * @return Cursor positioned to matching Alarm, if found
	 * @throws SQLException
	 *             if Alarm could not be found/retrieved
	 */
	public Cursor fetchAlarm(long rowId) throws SQLException {

		Cursor mCursor = mDb.query(true, DATABASE_TABLE,
				new String[] { KEY_ROWID, KEY_DESTINATION, KEY_HOUR,
						KEY_MINUTE, KEY_WARNTIME, KEY_MONTH, KEY_DAY, KEY_YEAR, KEY_ISON}, KEY_ROWID + "=" + rowId,
				null, null, null, null, null);

		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;

	}

	/**
	 * Update the alarm using the details provided. The alarm to be updated is
	 * specified using the rowId, and it is altered to use the title and body
	 * values passed in
	 * 
	 * @return true if the Alarm was successfully updated, false otherwise
	 */
	public boolean updateAlarm(long rowId, String destination, int hour,
			int minute, int warntime, int month, int day, int year, int isOn) {
		ContentValues args = new ContentValues();
		args.put(KEY_DESTINATION, destination);
		args.put(KEY_HOUR, hour);
		args.put(KEY_MINUTE, minute);
		args.put(KEY_WARNTIME, warntime);
		args.put(KEY_MONTH, month);
		args.put(KEY_DAY, day);
		args.put(KEY_YEAR, year);
		args.put(KEY_ISON, isOn);

		return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
	}
}
